package com.thunder.record_test;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.widget.Toast;
import com.thunder.record_test.fragments.RecordFragment;

/**
 * 主活动：双通道录音应用
 */
public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_RECORD_AUDIO = 1;
    
    private RecordFragment micFragment;
    private RecordFragment voiceRecognitionFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // 检查录音权限
        if (checkPermission()) {
            initFragments();
        } else {
            requestPermission();
        }
    }
    
    private boolean checkPermission() {
        return ActivityCompat.checkSelfPermission(this, 
                Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.RECORD_AUDIO},
                REQUEST_RECORD_AUDIO);
    }
    
    private void initFragments() {
        // 创建麦克风录音Fragment
        micFragment = RecordFragment.newInstance(
                MediaRecorder.AudioSource.MIC,
                "麦克风录音 (MIC)",
                "mic_recording.pcm");
                
        // 创建语音识别录音Fragment
        voiceRecognitionFragment = RecordFragment.newInstance(
                MediaRecorder.AudioSource.VOICE_RECOGNITION,
                "语音识别录音 (VOICE_RECOGNITION)",
                "voice_recognition_recording.pcm");
                
        // 添加Fragment到容器
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fragmentContainer1, micFragment)
                .replace(R.id.fragmentContainer2, voiceRecognitionFragment)
                .commit();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_RECORD_AUDIO) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initFragments();
            } else {
                Toast.makeText(this, "需要录音权限才能使用此功能", Toast.LENGTH_SHORT).show();
            }
        }
    }
}